from __future__ import absolute_import
from django.conf import settings
from celery import shared_task
from .toWeMsg import *
from .weChatSDK import requests_SDK, requests_Wechat_SDK
from .tempool import toMppsModelMessage
from .initialize import initialization
from .models import AllinpayStaffList
import json
import requests

import logging

logger = logging.getLogger(__name__)


@shared_task
def add(x, y):
    return x + y


@shared_task
def MyCeleryTest(*args, **kwargs):
    """测试任务"""
    print("out: test")
    return {"rescode": 200, "resmsg": "Test Task is ok"}


@shared_task
def MyInitialize(*args, **kwargs):
    """初始化启动任务"""
    initialization()
    return {"rescode": 200, "resmsg": "ok"}


@shared_task
def WeAppsUniformSend(touser, path, modelname, sargs):
    """小程序下发统一消息,"""
    def has_mopenid(openid):
        try:
            r = AllinpayStaffList.objects.get(openid=openid)
            return r.mopenid
        except BaseException as err:
            return None
    # 开始    
    openid = has_mopenid(touser)   
    if not openid: return {"rescode": 555, "resmsg": "发送实时消息失败"}
    
    # 实例化小程序api对象
    WX = requests_Wechat_SDK()
    WX.getConf()
    # url = "/cgi-bin/message/wxopen/template/uniform_send"
    url = "/cgi-bin/message/template/send"
    headers = WX.has_headers()
    headers["Content-Type"] = "application/json"
    params = {"access_token": WX.has_access_token()}

    # 收到客户新订单通知
    # 订单编号 {{character_string1.DATA}} # 字符串 	32位以内数字、字母或符号 	可数字、字母或符号组合
    # 订单类型 {{short_thing6.DATA}}
    # 客户名称 {{thing7.DATA}}
    # 订单时间 {{time2.DATA}}     # 时间 	24小时制时间格式（支持+年月日），支持填时间段，两个时间点之间用“~”符号连接 	例如：15:01，或：2019年10月1日 15:01
        
    data = {
           "touser":openid,
           "template_id":"t_Pb_6G4NdfKZ8DpC9LoLpSISF9x46xFQrfP520Zcyw",
           "url":"https://www.yisbar.com",  
           "miniprogram":{
             "appid":WX.Conf.get("appid"),
             "pagepath":path,
           },
        #    "client_msg_id":"MSG_000001",
           "data":{

                   "character_string1":{
                       "value":sargs[0]
                   },
                   "short_thing6": {
                       "value":sargs[1]
                   },
                   "thing7": {
                       "value":sargs[2]
                   },
                   "time2":{
                       "value":sargs[3]
                   }
           }        
    }
    
    # print("请求数据:", params, data)
    r = WX.do_post(
        url,
        headers=headers,
        params=params,
        data=json.dumps(data),
    )
    return r if r else {"error": "error"}

@shared_task
def WeAppsOpenidformSend(touser, path, modelname, sargs):
    """公众号模板消息给会员H5\n touser str openid,\n path str url,\n modelname str model_name,\n sargs List *args"""
    # 实例化小程序api对象
    WX = requests_Wechat_SDK()
    WX.getConf()
    # url = "/cgi-bin/message/wxopen/template/uniform_send"
    url = "/cgi-bin/message/template/send"
    headers = WX.has_headers()
    headers["Content-Type"] = "application/json"
    params = {"access_token": WX.has_access_token()}
    
    # 创建参数
    # path="https://we.hs6686.com/#/lol"
    tmpl =  toMppsModelMessage(modelname)
    if not tmpl:
        logger.warn(f"[WeMessage] 查询模板失败")
        raise ValueError(f"[WeMessage] 查询模板失败")
    args = [{"value":s} for s in sargs]
    if not len(tmpl["fields"]) == len(args):
        logger.warn(f"[WeMessage] 参数不匹配")
        raise ValueError(f"[WeMessage] 参数不匹配")
    data = {
           "touser":touser,
           "template_id":tmpl.get("mid"),
           "url":path,  
        #    "miniprogram":{
        #      "appid":WX.Conf.get("appid"),
        #      "pagepath":path,
        #    },
        #    "client_msg_id":"MSG_000001",
           "data":dict(zip(tmpl["fields"],args)) 
           
    }    
    # print("请求数据:", params, data)
    r = WX.do_post(
        url,
        headers=headers,
        params=params,
        data=json.dumps(data),
    )
    return r if r else {"error": "error"}
    
@shared_task
def DoSendWebSocketMessages(pid,info):
    """
    发送 WebSocket 实时消息
    加入房间: wss://api.yisbar.com/wschat/1000001/
    发送消息: http://DwebSocket:8000/hasSocket/ {"pid":1000001,"types":"xxx.ooo","info":"hello"}
    """
    headers = {"Content-Type": "application/json"}
    try:
        r = requests.post(
            url = "https://api.yisbar.com/hasSocket/", #headers=headers,
            data={"pid":pid,"types":"xxx.ooo","info":json.dumps(info)},verify=False)
    except BaseException as err:
        # logger.warn(f"[WebSocket] [err] {err}") 
        return {"rescode": 555, "resmsg": {err}}   
    else:                     
        return {"rescode": 200, "resmsg": r.text}

# 调用异步任务,返回任务ID
# res=MyCeleryTest.delay(args=[3,4])
# res=MyCeleryTest.apply_async(args=[3,4])
# res=MyCeleryTest.apply_async(kwds={'a':4,'b':4})
# print(res)  # 任务id号 :1f9faa34-452c-48df-b874-1c2824839675  查询结果的